package com.huoshan.im.server.filter;


import com.huoshan.im.server.ContextNaming;
import com.huoshan.im.server.messaging.MessageId;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import online.chazi.netkit.action.Action;
import online.chazi.netkit.action.ActionChain;
import online.chazi.netkit.action.ActionFilter;
import online.chazi.netkit.exception.ActionException;
import online.chazi.netkit.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 火山九日 on 2020-04-26 09:28
 */
@Slf4j
@Component
public class AuthorizeFilter implements ActionFilter {

    @SneakyThrows
    public void doFilter(Action action, Message message, ActionChain actionChain) throws ActionException {

        int messageId = message.getMessageId();
        if (messageId != MessageId.NORMAL_LOGIN.id
                && messageId != MessageId.SYS_LOGIN.id) {

            Object user = action.getSession().getAttribute(ContextNaming.SESSION_USER_ID);
            Object system = action.getSession().getAttribute(ContextNaming.SESSION_SYSTEM_ID);
            if (user == null && system == null) {
                // 由于客户端断线重连后业务消息与登录操作是并行的, 此自旋锁用于在登录操作没完成时而业务消息已经到达时候的特殊处理
                boolean lock = true;
                while (lock) {
                    Thread.sleep(200);
                    lock = false;
                    if (action.getSession().getAttribute(ContextNaming.SESSION_USER_ID) == null) {
                        action.getSession().sendMessageAndClose(new Message(MessageId.SRV_AUTH_NO_LOGIN.id));
                        return;
                    }
                }
            }

        }

        actionChain.doChain(action, message);

    }

}
